package lion.framework.core.db;

import java.lang.reflect.Method;

import lion.dev.lang.InterceptorAdaptor;
import lion.dev.lang.MapJ;
import lion.dev.lang.Proxy;
import lion.framework.core.conf.ConfigManager;

/**
 * 绑定到当前线程的DB，一个线程可以绑定多个DB，所有这些绑定到当前线程的db在同一个会话中，
 *
 * <pre>
 * time   2013 2013-4-24 上午11:29:05
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class SessionFactory {

	private static ThreadLocal<MapJ> currentDB = new ThreadLocal<>();

	public static void cleanSession() {

		MapJ currentDBs = getCurrentDBMap();
		if (currentDBs != null) {
			for (String key : currentDBs.keySet()) {
				DB db = currentDBs.getE(key);
				try {
					db.close();
				} catch (Exception e) {
				}
			}
		}
		currentDB.set(null);
	}

	public static DB getCurrentDB() {

		return getCurrentDB("default");
	}

	public static DB getCurrentDB(String name) {

		MapJ dbMap = currentDB.get();
		if (dbMap == null) {
			dbMap = new MapJ();
			currentDB.set(dbMap);
		}

		DB db = dbMap.getE(name);
		if (db == null || db.isClosed()) {
			db = Proxy.proxy(new DB(name), new InterceptorAdaptor() {

				@Override
				public boolean onBefore(Object... params) throws Exception {

					DB db = (DB) params[0];
					Method m = (Method) params[1];
					if (m.getName().startsWith("update") || m.getName().startsWith("save")) {
						if (!db.haveUncommitedTrans()) {
							db.setTransaction();
						}
					}
					return true;
				}
			});
			db.showSQL(ConfigManager.getConfig("framework").getBoolean("framework.showsql"));
			dbMap.put(name, db);
		}

		return db;
	}

	public static MapJ getCurrentDBMap() {

		return currentDB.get();
	}
}
